<?php

namespace App\Common\Util\Lock;

/**
 * Class FileLock
 */
class FileLock implements LockInterface
{
    private string $lockDir = __DIR__ . '/locks';

    private string $lockSign;
    /**
     * @var false|resource
     */
    private $fopen;

    public function __construct(string $lockSign)
    {
        $this->lockSign = strtr($lockSign, ['/' => "-", '\\' => '-', ':' => '.']);

        if (!is_dir($this->lockDir)) {
            mkdir($this->lockDir, 0777, true);
        }
        $this->fopen = fopen($this->lockDir . '/' . $this->lockSign, 'a+');
    }

    public static function up(string $lockSign, int $ttl = 5, int $waitTime = 0): bool|static
    {
        $fileLock = new self($lockSign);

        if (flock($fileLock->fopen, LOCK_EX)) {
            return $fileLock;
        }

        return false;
    }

    public function down(): void
    {
        flock($this->fopen, LOCK_UN);
    }
}